<template>
  <div
    :class="prefixCls"
    class="relative h-[100%] lt-md:px-10px lt-sm:px-10px lt-xl:px-10px lt-xl:px-10px"
  >
    <div class="relative mx-auto h-full flex">
      <div
        :class="`${prefixCls}__left flex-1 bg-gray-800 bg-opacity-10 relative p-30px lt-xl:hidden overflow-x-hidden overflow-y-auto`"
      >
        <!-- 左上角的 logo + 系统标题 -->
        <div class="relative flex items-center text-white">
          <img alt="" class="mr-10px h-48px w-48px" src="@/assets/imgs/logo.png" />
          <span class="text-20px font-bold">{{ underlineToHump(appStore.getTitle) }}</span>
        </div>
        <!-- 左边的背景图 + 欢迎语 -->
        <div class="h-[calc(100%-60px)] flex items-center justify-center">
          <TransitionGroup
            appear
            enter-active-class="animate__animated animate__bounceInLeft"
            tag="div"
          >
            <div key="1" style="text-align: center; margin-top: 3vw">
              <span class="text-3xl text-white">{{ t('login.welcomePrefix') }}</span>
              <span class="text-3xl text-#95cc01 font-bold">{{ t('login.welcomeSuffix') }}</span>
            </div>
            <div key="2" class="mt-5 text-14px font-normal text-white">
              <img src="@/assets/imgs/adwords.png" alt="" />
            </div>
          </TransitionGroup>
        </div>
      </div>
      <div
        class="relative flex-1 p-30px dark:bg-[var(--login-bg-color)] lt-sm:p-10px overflow-x-hidden overflow-y-auto"
      >
        <!-- 右上角的主题、语言选择 -->
        <div
          class="flex items-center justify-between text-white at-2xl:justify-end at-xl:justify-end"
        >
          <div class="flex items-center at-2xl:hidden at-xl:hidden">
            <img alt="" class="mr-10px h-48px w-48px" src="@/assets/imgs/logo.png" />
            <span class="text-20px font-bold">{{ underlineToHump(appStore.getTitle) }}</span>
          </div>
          <div class="flex items-center justify-end space-x-10px h-48px">
            <ThemeSwitch />
            <LocaleDropdown class="dark:text-white lt-xl:text-white" />
          </div>
        </div>
        <!-- 右边的登录界面 -->
        <Transition appear enter-active-class="animate__animated animate__bounceInRight">
          <div
            class="m-auto h-[calc(100%-60px)] w-[100%] flex items-center at-2xl:max-w-500px at-lg:max-w-500px at-md:max-w-500px at-xl:max-w-500px"
          >
            <el-form
              ref="formSmsLogin"
              :model="loginData.loginForm"
              :rules="rules"
              class="login-form"
              label-position="top"
              label-width="120px"
              size="large"
            >
              <el-row style="margin-right: -10px; margin-left: -10px">
                <!-- 租户名 -->
                <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
                  <el-form-item>
                    <LoginFormTitle style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
                  <el-form-item v-if="loginData.tenantEnable === 'true'" prop="tenantName">
                    <el-input
                      v-model="loginData.loginForm.tenantName"
                      :placeholder="t('login.tenantNamePlaceholder')"
                      :prefix-icon="iconHouse"
                      type="primary"
                      link
                    />
                  </el-form-item>
                </el-col>
                <!-- 手机号 -->
                <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
                  <el-form-item prop="mobileNumber">
                    <el-input
                      v-model="loginData.loginForm.mobileNumber"
                      :placeholder="t('login.mobileNumberPlaceholder')"
                      :prefix-icon="iconCellphone"
                    />
                  </el-form-item>
                </el-col>
                <!-- 验证码 -->
                <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
                  <el-form-item prop="code">
                    <el-row :gutter="5" justify="space-between" style="width: 100%">
                      <el-col :span="24">
                        <el-input
                          v-model="loginData.loginForm.code"
                          :placeholder="t('login.codePlaceholder')"
                          :prefix-icon="iconCircleCheck"
                        >
                          <!-- <el-button class="w-[100%]"> -->
                          <template #append>
                            <span
                              v-if="mobileCodeTimer <= 0"
                              class="getMobileCode"
                              style="cursor: pointer"
                              @click="getSmsCode"
                            >
                              {{ t('login.getSmsCode') }}
                            </span>
                            <span
                              v-if="mobileCodeTimer > 0"
                              class="getMobileCode"
                              style="cursor: pointer"
                            >
                              {{ mobileCodeTimer }}秒后可重新获取
                            </span>
                          </template>
                        </el-input>
                        <!-- </el-button> -->
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-col>
                <!-- 登录按钮 / 返回按钮 -->
                <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
                  <el-form-item>
                    <XButton
                      :loading="loginLoading"
                      :title="t('login.login')"
                      class="w-[100%]"
                      type="primary"
                      @click="signIn()"
                    />
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
                  <el-form-item>
                    <XButton
                      :loading="loginLoading"
                      :title="t('login.backLogin')"
                      class="w-[100%]"
                      @click="handleBackLogin()"
                    />
                  </el-form-item>
                </el-col> -->
              </el-row>
            </el-form>
          </div>
        </Transition>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { underlineToHump } from '@/utils'
import { useIcon } from '@/hooks/web/useIcon'

import { setTenantId, setToken } from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import {
  getTenantIdByName,
  sendSmsCode,
  smsLogin,
  getTenantByWebsite,
  socialLoginWithoutRedirect
} from '@/api/login'
import LoginFormTitle from '@/views/Login/components/LoginFormTitle.vue'
import { useFormValid, useLoginState } from '@/views/Login/components/useLogin'
import { ElLoading } from 'element-plus'
import * as authUtil from '@/utils/auth'
import router from '@/router'
import { ThemeSwitch } from '@/layout/components/ThemeSwitch'
import { LocaleDropdown } from '@/layout/components/LocaleDropdown'
import { useDesign } from '@/hooks/web/useDesign'
import { useAppStore } from '@/store/modules/app'

defineOptions({ name: 'SocialLoginMobile' })
const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('login')
const { t } = useI18n()
const message = useMessage()
const permissionStore = usePermissionStore()
const { currentRoute, push } = useRouter()
const formSmsLogin = ref()
const loginLoading = ref(false)
const iconHouse = useIcon({ icon: 'ep:house' })
const iconCellphone = useIcon({ icon: 'ep:cellphone' })
const iconCircleCheck = useIcon({ icon: 'ep:circle-check' })
const { validForm } = useFormValid(formSmsLogin)
const route = useRoute()
const appStore = useAppStore()
const rules = {
  tenantName: [required],
  mobileNumber: [required],
  code: [required]
}
const loginData = reactive({
  codeImg: '',
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  token: '',
  loading: {
    signIn: false
  },
  loginForm: {
    uuid: '',
    tenantName: import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT,
    mobileNumber: '',
    code: ''
  }
})
const smsVO = reactive({
  smsCode: {
    mobile: '',
    scene: 21 // 后台用户 - 手机号登录
  },
  loginSms: {
    mobile: '',
    code: '',
    socialType: undefined as unknown as string,
    socialCode: undefined as unknown as string,
    socialState: undefined as unknown as string
  }
})
const mobileCodeTimer = ref(0)
const redirect = ref<string>('')
const getSmsCode = async () => {
  await getTenantId()
  smsVO.smsCode.mobile = loginData.loginForm.mobileNumber
  await sendSmsCode(smsVO.smsCode).then(async () => {
    message.success(t('login.SmsSendMsg'))
    // 设置倒计时
    mobileCodeTimer.value = 60
    let msgTimer = setInterval(() => {
      mobileCodeTimer.value = mobileCodeTimer.value - 1
      if (mobileCodeTimer.value <= 0) {
        clearInterval(msgTimer)
      }
    }, 1000)
  })
}

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
// 获取租户 ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    const res = await getTenantIdByName(loginData.loginForm.tenantName)
    setTenantId(res)
  }
}
// 登录
const signIn = async () => {
  await getTenantId()
  const data = await validForm()
  if (!data) return
  ElLoading.service({
    lock: true,
    text: '正在加载系统中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  loginLoading.value = true
  smsVO.loginSms.mobile = loginData.loginForm.mobileNumber
  smsVO.loginSms.code = loginData.loginForm.code
  smsVO.loginSms.socialType = getUrlValue('type')
  smsVO.loginSms.socialCode = route?.query?.code as string
  smsVO.loginSms.socialState = route?.query?.state as string
  try {
    let res = await smsLogin(smsVO.loginSms)
    authUtil.setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }
    // 判断是否为SSO登录
    if (redirect.value.startsWith('http') || redirect.value.startsWith('https')) {
      window.location.href = redirect.value
    } else {
      res.state = route?.query?.state
      push({
        path: redirect.value || permissionStore.addRouters[0].path,
        query: { data: JSON.stringify(res) }
      })
    }
  } catch (e) {
  } finally {
    loginLoading.value = false
    setTimeout(() => {
      const loadingInstance = ElLoading.service()
      loadingInstance.close()
    }, 400)
  }
}
// tricky: 配合LoginForm.vue中redirectUri需要对参数进行encode，需要在回调后进行decode
function getUrlValue(key: string): string {
  const url = new URL(decodeURIComponent(location.href))
  return url.searchParams.get(key) ?? ''
}

// 尝试登录: 当账号已经绑定，socialLogin会直接获得token
const tryLogin = async () => {
  try {
    loginLoading.value = true
    const type = getUrlValue('type')
    const redirect = getUrlValue('redirect')
    const code = route?.query?.code as string
    const state = route?.query?.state as string
    let res = undefined as any
    // 跳过socialLogin
    // if (state.indexOf('skip_social_login') !== -1) {
    const tenantRes = await getTenantByWebsite(location.host)
    authUtil.setTenantId(tenantRes.id)
    const agentid = state.split('@@')[1].split('=')[1] as string
    res = await socialLoginWithoutRedirect(type, code, state, agentid)
    // } else {
    //   res = await signIn()
    // }
    authUtil.setToken(res)
    // 判断是否为SSO登录
    if (redirect.startsWith('http') || redirect.startsWith('https')) {
      window.location.href = redirect
    } else {
      res.state = state
      push({ path: redirect || '/', query: { data: JSON.stringify(res) } })
    }
    // router.push({ path: redirect || '/' })
  } catch (err) {
  } finally {
    loginLoading.value = false
  }
}

onMounted(() => {
  tryLogin()
})
</script>

<style lang="scss" scoped>
$prefix-cls: #{$namespace}-login;

.#{$prefix-cls} {
  overflow: auto;

  &__left {
    &::before {
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
      width: 100%;
      height: 100%;
      background-image: url('@/assets/imgs/login_bg.jpg');
      background-position: center;
      background-repeat: no-repeat;
      background-size: cover;
      content: '';
    }
  }
}
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}

.smsbtn {
  margin-top: 33px;
}
</style>
